package org.uoss.webapp.framework.struts2.security.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.util.UrlPathHelper;
import org.uoss.webapp.framework.http.HttpUtil;

public class AccessingPermissionFilter implements Filter {
	private UrlPathHelper urlPathHelper = new UrlPathHelper();
	
	@Override
	public void init(FilterConfig arg0) throws ServletException {
		System.out.println("AccessingPermissionFilter:init()");
	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain chain) throws IOException, ServletException {
		System.out.println("AccessingPermissionFilter:doFilter()");
		HttpServletRequest request = (HttpServletRequest)arg0;
		HttpServletResponse response = (HttpServletResponse)arg1;
		String jspurl = urlPathHelper.getLookupPathForRequest(request);
		if(!this.accessChecked(jspurl)){
			response.sendRedirect(request.getContextPath()+"/logon.jsp");
			return;
		}
		chain.doFilter(arg0, arg1);
	}
	
	@Override
	public void destroy() {
		System.out.println("AccessingPermissionFilter:destroy()");
	}
	
	private boolean accessChecked(String requesturl){
		if(requesturl.endsWith("logon.jsp")||requesturl.endsWith("index.jsp")){
			return true;
		}
		else if(HttpUtil.getHttpSession().getAttribute("USER_SESSION_KEY")!=null){
			return true;
		}
		else{
			return false;
		}
	}
}
